<template>
  <div class="dashboard-container">
    <!-- 数据卡片区域 -->
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card class="data-card orders">
          <div class="card-content">
            <div class="icon-wrapper">
              <el-icon><Document /></el-icon>
            </div>
            <div class="data-info">
              <div class="value">{{ statistics.orderCount }}</div>
              <div class="label">订单总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="data-card amount">
          <div class="card-content">
            <div class="icon-wrapper">
              <el-icon><Money /></el-icon>
            </div>
            <div class="data-info">
              <div class="value">¥{{ statistics.totalAmount }}</div>
              <div class="label">总收入</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="data-card pending">
          <div class="card-content">
            <div class="icon-wrapper">
              <el-icon><Timer /></el-icon>
            </div>
            <div class="data-info">
              <div class="value">{{ statistics.pendingCount }}</div>
              <div class="label">待处理订单</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="data-card completed">
          <div class="card-content">
            <div class="icon-wrapper">
              <el-icon><Select /></el-icon>
            </div>
            <div class="data-info">
              <div class="value">{{ statistics.completedCount }}</div>
              <div class="label">已完成订单</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <div class="chart-title">订单趋势</div>
          <div ref="orderChart" class="chart"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <div class="chart-title">收入趋势</div>
          <div ref="amountChart" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import {ref, onMounted, reactive} from 'vue'
import {Document, Money, Timer, Select} from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import {get} from '@/net'

const orderChart = ref(null)
const amountChart = ref(null)

const statistics = reactive({
  orderCount: 0,
  totalAmount: 0,
  pendingCount: 0,
  completedCount: 0
})

// 处理订单数据
const processOrderData = (orders) => {
  // 初始化数据结构
  const monthsData = new Map()

  // 找出最早和最晚的订单日期
  const dates = orders.map(order => new Date(order.create_time))
  const earliestDate = new Date(Math.min(...dates))
  const latestDate = new Date(Math.max(...dates))

  // 生成从最早月份开始的12个月
  const months = []
  const currentDate = new Date(earliestDate)

  for (let i = 0; i < 12; i++) {
    const monthStr = `${currentDate.getFullYear()}-${String(currentDate.getMonth() + 1).padStart(2, '0')}`
    months.push(monthStr)
    monthsData.set(monthStr, {
      orderCount: 0,
      amount: 0
    })
    currentDate.setMonth(currentDate.getMonth() + 1)
  }

  // 统计每个月的订单数和金额
  orders.forEach(order => {
    const orderDate = new Date(order.create_time)
    const orderMonth = `${orderDate.getFullYear()}-${String(orderDate.getMonth() + 1).padStart(2, '0')}`

    if (monthsData.has(orderMonth)) {
      const monthData = monthsData.get(orderMonth)
      monthData.orderCount += 1
      monthData.amount += Number(order.money)
    }
  })

  // 转换数据格式
  const orderCounts = months.map(month => monthsData.get(month).orderCount)
  const amounts = months.map(month => monthsData.get(month).amount)

  return {
    months,
    orderCounts,
    amounts
  }
}

// 初始化订单图表
const initOrderChart = (data) => {
  const chart = echarts.init(orderChart.value)
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: '{b}: {c} 个订单'
    },
    grid: {
      top: '15%',
      left: '3%',
      right: '4%',
      bottom: '12%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: data.months,
      axisLabel: {
        interval: 0,
        rotate: 45,
        fontSize: 12
      },
      axisTick: {
        alignWithLabel: true
      }
    },
    yAxis: {
      type: 'value',
      minInterval: 1,
      splitNumber: 5,
      min: 0,
      name: '订单数量'
    },
    series: [{
      name: '月度订单数',
      data: data.orderCounts,
      type: 'bar',
      color: '#409EFF',
      barWidth: '40%',
      showBackground: true,
      backgroundStyle: {
        color: 'rgba(180, 180, 180, 0.1)'
      },
      itemStyle: {
        borderRadius: [4, 4, 0, 0]
      },
      label: {
        show: true,
        position: 'top',
        formatter: '{c}'
      }
    }]
  }
  chart.setOption(option)
}

// 初始化收入图表
const initAmountChart = (data) => {
  const chart = echarts.init(amountChart.value)
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: '{b}: ¥{c}'
    },
    grid: {
      top: '15%',
      left: '3%',
      right: '4%',
      bottom: '12%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: data.months,
      axisLabel: {
        interval: 0,
        rotate: 45,
        fontSize: 12
      },
      axisTick: {
        alignWithLabel: true
      }
    },
    yAxis: {
      type: 'value',
      name: '收入金额',
      axisLabel: {
        formatter: '¥{value}'
      }
    },
    series: [{
      name: '月度收入',
      data: data.amounts,
      type: 'line',
      smooth: true,
      symbolSize: 8,
      lineStyle: {
        width: 3,
        color: '#67C23A'
      },
      itemStyle: {
        color: '#67C23A'
      },
      label: {
        show: true,
        position: 'top',
        formatter: '¥{c}'
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [{
            offset: 0,
            color: 'rgba(103,194,58,0.3)'
          }, {
            offset: 1,
            color: 'rgba(103,194,58,0.1)'
          }]
        }
      }
    }]
  }
  chart.setOption(option)
}
// 获取数据并更新统计信息
const fetchData = () => {
  get('/api/order/getAllOrderList', (res) => {
    const orders = res

    // 更新统计数据
    statistics.orderCount = orders.length
    statistics.totalAmount = orders.reduce((sum, order) => sum + Number(order.money), 0)
    statistics.pendingCount = orders.filter(order => order.status === 0).length
    statistics.completedCount = orders.filter(order => order.status === 1).length

    // 处理并显示图表数据
    const chartData = processOrderData(orders)
    initOrderChart(chartData)
    initAmountChart(chartData)
  }, (error) => {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
  })
}

onMounted(() => {
  fetchData()

  // 监听窗口大小变化，重绘图表
  window.addEventListener('resize', () => {
    orderChart.value && echarts.getInstanceByDom(orderChart.value)?.resize()
    amountChart.value && echarts.getInstanceByDom(amountChart.value)?.resize()
  })
})
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  background: #f5f7fa;
}

.data-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.card-content {
  display: flex;
  align-items: center;
  padding: 10px;
}

.icon-wrapper {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
}

.orders .icon-wrapper {
  background-color: #ecf5ff;
  color: #409eff;
}

.amount .icon-wrapper {
  background-color: #f0f9eb;
  color: #67c23a;
}

.pending .icon-wrapper {
  background-color: #fdf6ec;
  color: #e6a23c;
}

.completed .icon-wrapper {
  background-color: #f0f9eb;
  color: #67c23a;
}

.data-info .value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 4px;
}

.data-info .label {
  color: #909399;
}

.chart-row {
  margin-top: 20px;
}

.chart-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.chart-title {
  font-size: 16px;
  font-weight: bold;
  margin: 16px;
}

.chart {
  height: 350px;
  padding: 10px;
}
</style>